package com.vt.common.security.social;

import com.google.common.base.Joiner;
import com.vt.common.core.constant.SecurityConstants;
import com.vt.common.security.exception.SocialAuthenticationException;
import com.vt.common.security.mobile.MobileAuthenticationEntryPoint;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 社交登录验证filter
 */
public class SocialAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    private static final String SPRING_SECURITY_FORM_SOCIAL_CODE = "code";
    private static final String SPRING_SECURITY_FORM_SOCIAL_CLIENT = "client";
    private AuthenticationEntryPoint authenticationEntryPoint = new MobileAuthenticationEntryPoint();

    @Getter
    @Setter
    private boolean postOnly = true;
    @Getter
    @Setter
    private AuthenticationEventPublisher eventPublisher;

    public SocialAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.SOCIAL_TOKEN_URL, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String code = obtainCode(request);
        String clientKey = obtainClientId(request);

        SocialAuthenticationToken socialAuthenticationToken = new SocialAuthenticationToken(Joiner.on("@").join(clientKey, code));

        setDetails(request, socialAuthenticationToken);

        Authentication authResult = null;
        try {
            authResult = this.getAuthenticationManager().authenticate(socialAuthenticationToken);

            eventPublisher.publishAuthenticationSuccess(authResult);
            SecurityContextHolder.getContext().setAuthentication(authResult);

        } catch (Exception failed) {
            SecurityContextHolder.clearContext();
            logger.debug("social Authentication request failed: " + failed);

            eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
                    new PreAuthenticatedAuthenticationToken("access-token", "N/A"));

            failed = new SocialAuthenticationException();
            try {
                authenticationEntryPoint.commence(request, response,
                        new UsernameNotFoundException(failed.getMessage(), failed));
            } catch (Exception e) {
                logger.error("social authenticationEntryPoint handle error:{}", failed);
            }
        }

        return authResult;
    }

    private String obtainCode(HttpServletRequest request) {
        return request.getParameter(SPRING_SECURITY_FORM_SOCIAL_CODE);
    }

    private String obtainClientId(HttpServletRequest request) {
        return request.getParameter(SPRING_SECURITY_FORM_SOCIAL_CLIENT);
    }

    private void setDetails(HttpServletRequest request,
                            SocialAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}

